package com.jtw.common.util;

import com.jtw.common.bean.vo.FileTree;

import java.io.File;

/**
 * DESCRIPT:
 *
 * @author cjsky666
 * @date 2019/5/15 11:02
 */
public class FileUtils {

    /**
     * 获取制定目录下的所有文件树模型
     * @param dir 指定的文件
     * @return
     */
    public static FileTree getFileTree(File dir){
        FileTree fileTree = new FileTree();
        if(!dir.exists()){
            return fileTree;
        }
        //组建目录结构
        fileTree.setPath(dir.getAbsolutePath());
        fileTree.setName(dir.getName());
        fileTree.setIsDirectory(dir.isDirectory()?1:0);
        fileTree.setSize(org.apache.commons.io.FileUtils.byteCountToDisplaySize(dir.length()));
        File [] files = dir.listFiles();

        for(File file:files){
            if(file.isDirectory()){
                fileTree.getSubTree().add(getFileTree(file));
            }else{
                FileTree fileTree1 = new FileTree();
                fileTree1.setPath(file.getAbsolutePath());
                fileTree1.setName(file.getName());
                fileTree1.setIsDirectory(file.isDirectory()?1:0);
                fileTree1.setSize(org.apache.commons.io.FileUtils.byteCountToDisplaySize(file.length()));
                fileTree.getSubTree().add(fileTree1);
            }
        }
        return fileTree;
    }
}
